﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace GTA
{
    public partial class FrmNotityIcon : BaseFormAlerts
    {
        #region Local Objects
        private Int32 width_position;
        private Int32 height_position;
        #endregion

        #region Start Form
        public FrmNotityIcon(List<BusinessEntity.Configuration.Alert> alerts)
            : base(alerts)
        {
            InitializeComponent();

            this.Size = new Size(this.Size.Width, 2);
            width_position = (Screen.PrimaryScreen.WorkingArea.Width) - this.Size.Width - 10;
            height_position = Screen.PrimaryScreen.WorkingArea.Height;
        }
        private void FrmNotityIcon_Load(object sender, EventArgs e)
        {
            StartForm();
        }
        private void StartForm()
        {
            this.Location = new Point(width_position, height_position);
            LoadAlerts();
        }
        #endregion

        #region Events
        private void cmdClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void lstAlerts_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            SortList(lstAlerts, e.Column == 0 ? OrdenacaoListView.Tipo.Numerica : OrdenacaoListView.Tipo.Alfabetica, ref columnOrder, ref sortOrder, e.Column);
        }
        private void lstAlerts_DoubleClick(object sender, EventArgs e)
        {
            ShowAlertDetails();
        }
        private void lstAlerts_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                DeleteSelectedAlert();
        }
        private void lstAlerts_Resize(object sender, EventArgs e)
        {
            lstAlerts.Columns[1].Width = lstAlerts.Width - lstAlerts.Columns[0].Width - lstAlerts.Columns[2].Width - 23;
        }
        private void detalhesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowAlertDetails();
        }
        private void inativarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeactivateSelectedAlert();
        }
        private void excluirToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteSelectedAlert();
        }
        private void minutosToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetAlertSleep(BusinessEntity.Configuration.AlertSleepType.FiveMinutes);
        }
        private void minutosToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SetAlertSleep(BusinessEntity.Configuration.AlertSleepType.TenMinutes);
        }
        private void minutosToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            SetAlertSleep(BusinessEntity.Configuration.AlertSleepType.FifteenMinutes);
        }
        private void minutosToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            SetAlertSleep(BusinessEntity.Configuration.AlertSleepType.ThirtyMinutes);
        }
        private void horaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetAlertSleep(BusinessEntity.Configuration.AlertSleepType.OneHour);
        }
        private void diaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetAlertSleep(BusinessEntity.Configuration.AlertSleepType.OneDay);
        }
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            HandleContextMenuState();
        }
        #endregion

        #region Methods
        private void HandleContextMenuState()
        {
            detalhesToolStripMenuItem.Enabled = lstAlerts.SelectedItems.Count == 1;
            pausarToolStripMenuItem.Enabled = lstAlerts.SelectedItems.Count == 1;
            inativarToolStripMenuItem.Enabled = lstAlerts.SelectedItems.Count == 1;
            excluirToolStripMenuItem.Enabled = lstAlerts.SelectedItems.Count == 1;
        }
        private void LoadAlerts()
        {
            Int32 selectedId = lstAlerts.SelectedItems.Count > 0 ? Convert.ToInt32(lstAlerts.SelectedItems[0].SubItems[0].Text) : Int32.MinValue;
            lstAlerts.Items.Clear();

            //Remove all alerts which doesn't has detail descriptions about qualified tasks.
            if (alerts != null)
                alerts.RemoveAll(it => String.IsNullOrEmpty(it.Description));

            if (alerts != null && alerts.Count > 0)
            {
                foreach (BusinessEntity.Configuration.Alert itemAlert in alerts)
                {
                    ListViewItem listItem = new ListViewItem(itemAlert.ID.ToString());
                    listItem.SubItems.Add(itemAlert.Name);
                    listItem.SubItems.Add(itemAlert.Description);
                    lstAlerts.Items.Add(listItem);
                }

                if (selectedId != Int32.MinValue)
                {
                    foreach (ListViewItem listItem in lstAlerts.Items)
                    {
                        if (Convert.ToInt32(listItem.SubItems[0].Text).CompareTo(selectedId) == 0)
                        {
                            listItem.Selected = true;
                            break;
                        }
                    }
                }
            }
        }
        private void RefreshAlertList()
        {
            BusinessLogic.Configuration bl = new GTA.BusinessLogic.Configuration();
            alerts = bl.ListAlerts(Program.LoggedUser,
                                   new GTA.BusinessEntity.Configuration.AlertFilter()
                                   {
                                       State = GTA.BusinessEntity.Configuration.AlertState.Ativo,
                                       CheckSleep = true
                                   });
            if (alerts != null && alerts.Count > 0)
            {
                alerts = bl.FillAlertsDescription(alerts, Program.LoggedUser);
                alerts.RemoveAll(it => String.IsNullOrEmpty(it.Description));
            }
            UpdateAlerts(alerts);
        }
        public override void UpdateAlerts(List<GTA.BusinessEntity.Configuration.Alert> alerts)
        {
            base.UpdateAlerts(alerts);
            //Reload the alerts.
            LoadAlerts();
        }
        private void ShowAlertDetails()
        {
            try
            {
                if (lstAlerts.SelectedItems.Count == 1)
                {
                    //String alertDetails = BusinessLogic.Configuration.GetInstance().GetAlertsTextDescription(alerts.Find(it => it.ID.CompareTo(Convert.ToInt32(lstAlerts.SelectedItems[0].SubItems[0].Text)) == 0), Program.LoggedUser);
                    FrmTextArea wd = new FrmTextArea(lstAlerts.SelectedItems[0].SubItems[2].Text);
                    wd.ShowInTaskbar = false;
                    wd.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                HandleException("Abrir os detalhes do alerta", ex);
            }
        }
        private void DeleteSelectedAlert()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (lstAlerts.SelectedItems.Count == 1)
                {
                    if (MessageBox.Show("Deseja realmente excluir o alerta selecionado?", "Questão", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        new BusinessLogic.Configuration().DeleteAlert(Convert.ToInt32(lstAlerts.SelectedItems[0].SubItems[0].Text));
                        MessageBox.Show("Alerta excluído com sucesso!", "Confirmação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        RefreshAlertList();
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Excluir o alerta selecionado.", ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        private void DeactivateSelectedAlert()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (lstAlerts.SelectedItems.Count == 1)
                {
                    if (MessageBox.Show("Deseja realmente desativar o alerta selecionado?", "Questão", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        new BusinessLogic.Configuration().UpdateAlertState(Convert.ToInt32(lstAlerts.SelectedItems[0].SubItems[0].Text), GTA.BusinessEntity.Configuration.AlertState.Inativo);
                        MessageBox.Show("Alerta desativado com sucesso!", "Confirmação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        RefreshAlertList();
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Inativar o alerta selecionado.", ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        private void SetAlertSleep(GTA.BusinessEntity.Configuration.AlertSleepType alertSleepType)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (lstAlerts.SelectedItems.Count == 1)
                {
                    if (MessageBox.Show("Deseja realmente pausar o alerta selecionado?", "Questão", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        new BusinessLogic.Configuration().UpdateAlertSleep(Convert.ToInt32(lstAlerts.SelectedItems[0].SubItems[0].Text), alertSleepType);
                        MessageBox.Show("Alerta pausado com sucesso!", "Confirmação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        RefreshAlertList();
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException("Definir uma pausa para o alerta.", ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        #endregion
    }
}
